package cn.edu.pzhu.servlet;

import java.io.IOException;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import cn.edu.pzhu.pojo.FileMsg;
import cn.edu.pzhu.service.FileMsgService;
import cn.edu.pzhu.service.imp.FileMsgServiceImp;
import cn.edu.pzhu.util.ListSortUtil;
import cn.edu.pzhu.util.PageUtil;

/**
 * Servlet implementation class ListSortServlet
 */
@WebServlet("/listsort")
public class ListSortServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public ListSortServlet() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) 
			throws ServletException, IOException {
		String key = request.getParameter("key");
		String page = request.getParameter("page");
		String num = request.getParameter("num");
		String my = request.getParameter("my");
		String count = request.getParameter("count");
		
//		System.out.println(count);
		
		String keyword = null;
		if(key != null) {
			try {
				keyword = key;
			} catch (Exception e) {
				keyword = "username";
			}
		}
		
		int p = 1, n = 10;
		if(page!=null) { //"-1"
			try {
				p = Integer.parseInt(page);
			} catch (Exception e) {
				p = 1;
			}
		}
		if(num!=null) {
			try {
				n = Integer.parseInt(num);
			} catch (Exception e) {
				n = 10;
			}
		}
		
		ListSortUtil listSortUtil = new ListSortUtil();
		List<FileMsg> list = (List<FileMsg>) request.getSession().getAttribute("prelist");
		Comparator<FileMsg> comparator = listSortUtil.getComparator(keyword);
		Collections.sort(list, comparator); 
		if ("2".equals(count)) {
	        Collections.reverse(list);
	    }
		List<FileMsg> pageList=PageUtil.splitList(list, p, n);//调用工具类切分列表
		request.getSession().setAttribute("list", pageList);
			
		String address = "listsort";
		//导航栏
		StringBuffer bar = PageUtil.createBarByPara(list, p, n, address ,keyword, my, count);
		request.getSession().setAttribute("bar", bar);
		request.getSession().setAttribute("num", num);
		if("1".equals(my)) {
			response.sendRedirect("showmysortfile.jsp");
		}
		if("0".equals(my)) {
			response.sendRedirect("showsortfile.jsp");
		}
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		doGet(request, response);
	}

}
